<?php namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests\UserRequest;
use App\Http\Controllers\Controller;
use App\Services\UserService;
use App\Models\Role;
use App\User;

class UserController extends Controller
{

    public function getIndex(UserService $userService, Request $request)
    {
        return view('admin.user.users', [
            'request' => $request,
            'genders' => User::$_gender,
            'roles' => Role::all(),
            'users' => $userService->getList($request)
        ]);
    }

    public function getAdd()
    {
        return view('admin.user.add', [
            'genders' => User::$_gender,
            'roles' => Role::all()
        ]);
    }

    public function postAdd(UserService $userService, UserRequest $userRequest)
    {
        $userService->create([
            'name' => $userRequest->input('name'),
            'email' => $userRequest->input('email'),
            'phone' => $userRequest->input('phone'),
            'gender' => $userRequest->input('gender', 'male'),
            'address' => $userRequest->input('address'),
            'role_id' => $userRequest->input('role_id', 1),
            'password' => $userRequest->input('password', '000000')
        ]);
        return $this->bSuccess('添加用户成功', true, ['tabid' => 'users']);
    }

    public function getEdit($id)
    {
        return view('admin.user.edit', [
            'genders' => User::$_gender,
            'user' => User::find($id),
            'roles' => Role::all()
        ]);
    }

    public function postEdit(UserService $userService, UserRequest $userRequest)
    {
        $userService->update($userRequest->input('id'), [
            'name' => $userRequest->input('name'),
            'phone' => $userRequest->input('phone'),
            'gender' => $userRequest->input('gender', 'male'),
            'address' => $userRequest->input('address'),
            'role_id' => $userRequest->input('role_id', '1')
        ]);
        return $this->bSuccess('修改用户成功', true, ['tabid' => 'users']);
    }

    public function getDelete($id, UserService $userService)
    {
        $userService->delete($id);
        return $this->bSuccess('删除用户成功', false);
    }
}